package com.jiang.demo.controller;

import com.jiang.demo.channel.DemoChannel;
import com.jiang.demo.channel.Message;
import com.jiang.starter.redis.cache.aop.Cache;
import com.jiang.starter.redis.lock.aop.Lock;
import com.jiang.starter.redis.consts.Time;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RedisController {

    @Cache(cacheNames = "demo", key = "#id", expire = 60 * Time.SECOND)
    @GetMapping("/cache")
    @SneakyThrows
    public String demo(Long id) {
        log.info(String.format("执行cache...{}...", (id)));
        Thread.sleep(5000);
        return "cache";
    }

    @Lock(key = "#id")
    @GetMapping("/lock")
    @SneakyThrows
    public String lock(Long id) {
        log.info(String.format("执行lock...{}...", (id)));
        Thread.sleep(5000);
        return "lock";
    }

    @Autowired
    DemoChannel demoChannel;

    @GetMapping("/publish")
    public String publish(String msg) {
        demoChannel.publish(new Message(333L, msg));
        return "OK";
    }
    @GetMapping("/subscribe")
    public String subscribe(Long id) {
        System.out.println(String.format("id{}添加了订阅者", id));
        demoChannel.subscribe(message -> {
            System.out.println(id.toString() + " " + message.toString());
        });
        return "OK";
    }
    @GetMapping("/receive")
    public Message publish() {
        return demoChannel.receive();
    }

}
